<template>
  <el-card class="box-card">
    <div slot="header" class="clearfix">
      <span>更换头像</span>
    </div>
    <div>
      <!-- 图片，用来展示用户选择的头像 -->
      <img src="../../../assets/images/avatar.jpg" alt="" class="preview" v-if="avatar === ''"/>
      <img :src="avatar" alt="" class="preview" v-else/>

      <!-- 按钮区域 -->
      <div class="btn-box">
        <input type="file" style="display: none;" ref="fileRef" accept="image/*" @change="fileChange" />
        <el-button type="primary" icon="el-icon-plus" @click="chooseImg">选择图片</el-button>
        <el-button type="success" icon="el-icon-upload" :disabled="avatar === ''" @click="uploadImg">上传头像</el-button>
      </div>
    </div>
  </el-card>
</template>

<script>
export default {
  name: 'UserAvatar',
  data() {
    return {
      avatar: ''
    }
  },
  methods: {
    chooseImg() {
      this.$refs.fileRef.click()
    },
    fileChange(e) {
      const files = e.target.files
      if (files.length === 0) {
        console.log('没有选择图片')
      } else {
        console.log('选择了图片')
        console.log(files[0])
        const fr = new FileReader()
        fr.readAsDataURL(files[0])
        fr.onload = e => {
          // console.log(e.target.result)
          this.avatar = e.target.result
        }
      }
    },
    async uploadImg() {
      const { data: res } = await this.$http.patch('/my/update/avatar', {
        avatar: this.avatar
      })
      if (res.code === 0) {
        // 更新头像成功
        this.$message.success(res.message)
        // 调用获取用户信息接口，拿到最新头像
        this.$store.dispatch('getUserInfo')
      } else {
        // 更新头像失败
        this.$message.error(res.message)
      }
    }
  }
}
</script>

<style lang="less" scoped>
.btn-box {
  margin-top: 10px;
}
.preview {
  width: 350px;
  height: 350px;
  object-fit: cover;
}
</style>
